package net.bolue.console.model;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.bolue.sysmng.db.DbOpUtil;
import net.bolue.sysmng.exception.BolueException;
import net.bolue.sysmng.model.ReportResModel;
import net.bolue.sysmng.tblbean.RepCnd;
import net.bolue.sysmng.tblbean.RepRes;
import net.bolue.sysmng.util.PageVo;
import net.bolue.web.mvc.ActionResult;
import net.bolue.web.util.RequestUtil;

/**
 * 报表业务类
 * @author Administrator
 *
 */
public class ReportModel extends BusiBase{

	private RepRes repRes = null;
	public ReportModel(){
		super();
	}
	
	public ReportModel(HttpServletRequest request,RepRes repRes) {
		super(request);
		this.repRes = repRes;
	}

	/**
	 * 查询数据
	 * @param request
	 * @param response
	 * @return
	 * @throws BolueException
	 */
	public ActionResult listData()throws BolueException {
		if(repRes==null){
			return null;
		}
		Map<String,Object> whereMap = putWhereData();
		PageVo pageVo = new PageVo();
		String dbResId = this.repRes.getSubSys();
		String sqlTp = this.repRes.getDataSrc();
		String spage = request.getParameter("page");
		String srows = request.getParameter("rows");
		String sort = request.getParameter("sort");
		String order = request.getParameter("order");
		Integer page = 1;
		Integer rows = 10;
		if(spage!=null){
			page = Integer.parseInt(spage);
		}
		if(srows!=null){
			rows = Integer.parseInt(srows);
		}
		pageVo.setNowPage(page);
		pageVo.setMaxResults(rows);
		pageVo.deal();
		if(sort!=null&&!"".equals(sort)){
			pageVo.setSortname(sort);
		}
		if(order!=null&&!"".equals(order)){
			pageVo.setSortorder(order);
		}
		DbOpUtil dbOpUtil = new DbOpUtil(dbResId);
		List<Map<String,Object>> dataList = dbOpUtil.query(sqlTp, whereMap,pageVo);
		Map<String,Object> pageMap = new HashMap<String,Object>();
		
		ActionResult actionResult = new ActionResult();
		pageMap.put("total", pageVo.getTotalcount());
		pageMap.put("rows", dataList);
		actionResult.setData(pageMap);
		actionResult.setResult(true);
		return actionResult;
	}
	
	/**
	 * 封装查询条件
	 * @return
	 * @throws BolueException
	 */
	public Map<String,Object> putWhereData()throws BolueException{
		ReportResModel reportResModel = new ReportResModel(request);
		List<RepCnd> repCndList = reportResModel.getRepCndList(this.repRes.getSubSys(), this.repRes.getRepId());
		
		Map<String,Object> whereMap = new HashMap<String,Object>();
		if(repCndList!=null&&repCndList.size()>0){
			for(int i=0;i<repCndList.size();i++){
				RepCnd repCnd = repCndList.get(i);
				String cndName = repCnd.getCndName();
				String cndValue = RequestUtil.getCndParamValue(request, cndName);
				if(cndValue!=null&&!"".equals(cndValue)){
					Object parseValue =  RequestUtil.parseValue(repCnd.getJType(),cndValue);
					whereMap.put(cndName, parseValue);
				}
			}
		}
		return whereMap;
	}
}
